package com.elite.rediszset.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.ZParams;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 排行榜的控制
 */
@RestController
public class RankingController {

    //喜欢的key的前缀
    private static final String LIKE_PREFIX="like:";

    private static final String USER_PREFIX="user:";
    @Resource
    Jedis jedis;

    /**
     * 加入排行榜
     * @param userId 用户Id
     * @param score  分数
     * @return
     */
    @PostMapping("/joinRanking")
    public String joinRanking(String userId,double score){
        Long zadd = jedis.zadd("voteing:10:ranking", score, userId);
        return zadd.toString();
    }
    /**
     * 点赞的存储
     */
    @PostMapping("/likePost")
    public String likePost(String postId,String userId){
        String key = LIKE_PREFIX+postId;
        Long now = System.currentTimeMillis();
        Long zadd = jedis.zadd(key, now.doubleValue(), userId);
        return zadd.toString();
    }
    /**
     * 取消点赞
     */
    @PostMapping("/unlikePost")
    public String unlikePost(String postId,String userId){
        String key = LIKE_PREFIX+postId;
        Long zadd = jedis.zrem(key, userId);
        return zadd.toString();
    }
    /**
     * 点赞列表
     */
    @PostMapping("/getLikes")
    public List<String> getLikes( String postId){
        String key = LIKE_PREFIX+postId;
        ZParams zParams = new ZParams();
        return jedis.zrangeByScoreWithScores(key,"-inf","+inf",0,-1)
                .stream().map(tuple -> {
                  String userId = tuple.getElement();
                  return userId;
                }).collect(Collectors.toList());

    }

}
